<?php

// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla modelitem library
jimport('joomla.application.component.modellist');

class CouponsModelCoupons extends JModelList
{       
    public function __construct()
    {
        $this->_db = JFactory::getDbo();
        parent::__construct();
    }    

    protected function getListQuery() 
    {
        $query = $this->_db->getQuery(true);
        $query->select('id, productName, catid, userId, productPrice, discountPercent, startSellingDate, endSellingDate, target, state');
        $query->from('#__coupons');
        
        // Filter by published state
        $published = $this->getState('filter.state');
        if (is_numeric($published)) 
                $query->where('state = '.(int) $published);
         elseif ($published === '') 
                $query->where('(state IN (0, 1))');

        // Filter by category.
        $categoryId = $this->getState('filter.category_id');
        if (is_numeric($categoryId)) 
                $query->where('catid = '.(int) $categoryId);
        
        $query->order('userId');
        
        return $query;
    }
    
    public function getTable($type = 'Coupon', $prefix = 'Table', $config = array())
    {
            return JTable::getInstance($type, $prefix, $config);
    }
    
    public function delete()
    {
        return LogicHelper::deleteRecordsList('Coupon');
    }
  /*  
    private function getCoupons($ids) 
    {
        $where .= " where ";
        $countIds = count($ids);
        for($i=0; $i < $countIds; $i++)
        {
             $where .= ' id='.mysql_real_escape_string($ids[$i]);
             if($i != $countIds-1)
                 $where.=' OR ';
        }
        $data = $this->_getList('SELECT * FROM #__coupons '.$where);
        return $data;
    }
    */
    private function getObject($table,$id)
    {
        $query = "SELECT * FROM {$table} where id=".mysql_real_escape_string($id);
        $objects = $this->_getList($query);
        return $objects[0];
    }
    
    public function getCategory($id)
    {
        return $this->getObject('#__categories', $id);
    }
    
    public function getShop($id)
    {
        return $this->getObject('#__shops', $id);
    }
    
    /*
    * Method to auto-populate the model state.
    *
    * Note. Calling getState in this method will result in recursion.
    *
    * @since	1.6
    */
    protected function populateState($ordering = null, $direction = null)
    {
        $state = $this->getUserStateFromRequest($this->context.'.filter.state', 'filter_state', '', 'string');
        $this->setState('filter.state', $state);

        $categoryId = $this->getUserStateFromRequest($this->context.'.filter.category_id', 'filter_category_id', '');
        $this->setState('filter.category_id', $categoryId);
    }
}
?>
